<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>高性能弹幕系统</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
<div class="container">
    <div class="header">
        <h1>高性能弹幕系统</h1>
        <p>基于Netty和RocketMQ实现实时弹幕传输</p>
    </div>

    <div class="barrage-display" id="barrageDisplay">
        <!-- 弹幕将在这里显示 -->
    </div>

    <div class="control-panel">
        <div class="input-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" th:value="'User-' + ${userId.substring(0, 8)}" placeholder="用户名">
            <input type="hidden" id="userId" th:value="${userId}">
        </div>

        <div class="input-group">
            <label for="message">弹幕内容:</label>
            <input type="text" id="message" placeholder="输入弹幕内容..." maxlength="100">
            <button onclick="sendBarrage()">发送</button>
        </div>

        <div class="input-group">
            <label for="color">颜色:</label>
            <select id="color">
                <option value="#FFFFFF">白色</option>
                <option value="#FF0000">红色</option>
                <option value="#00FF00">绿色</option>
                <option value="#0000FF">蓝色</option>
                <option value="#FFFF00">黄色</option>
                <option value="#FF00FF">紫色</option>
            </select>
            <div class="color-preview" id="colorPreview" style="background-color: #FFFFFF;"></div>

            <label for="fontSize">字体:</label>
            <select id="fontSize">
                <option value="16">小</option>
                <option value="20" selected>中</option>
                <option value="24">大</option>
            </select>

            <label for="position">位置:</label>
            <select id="position">
                <option value="normal">滚动</option>
                <option value="top">顶部</option>
                <option value="bottom">底部</option>
            </select>
        </div>

        <div class="status connecting" id="connectionStatus">
            正在连接到服务器...
        </div>

        <div class="stats">
            <div class="stat-item">
                <span class="stat-value" id="onlineCount">0</span>
                <span class="stat-label">在线人数</span>
            </div>
            <div class="stat-item">
                <span class="stat-value" id="sentCount">0</span>
                <span class="stat-label">发送数量</span>
            </div>
            <div class="stat-item">
                <span class="stat-value" id="receivedCount">0</span>
                <span class="stat-label">接收数量</span>
            </div>
        </div>
    </div>
</div>

<script th:inline="javascript">
    let ws;
    let userId = /*[[${userId}]]*/ '';
    let sentCount = 0;
    let receivedCount = 0;
    let onlineCount = 0;

    // 页面加载完成后连接WebSocket
    window.onload = function() {
        connectWebSocket();
        
        // 监听颜色选择变化
        document.getElementById('color').addEventListener('change', function() {
            document.getElementById('colorPreview').style.backgroundColor = this.value;
        });
        
        // 监听回车键发送消息
        document.getElementById('message').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendBarrage();
            }
        });
    };

    // 连接WebSocket
    function connectWebSocket() {
        const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
        const host = window.location.host;
        // 修复WebSocket URL构建逻辑
        let wsUrl;
        if (host.includes(':')) {
            // 如果主机名包含端口，则替换为8090
            const hostParts = host.split(':');
            wsUrl = protocol + hostParts[0] + ':8090/barrage';
        } else {
            // 如果主机名不包含端口，则直接添加8090
            wsUrl = protocol + host + ':8090/barrage';
        }
        
        console.log('Attempting to connect to WebSocket at:', wsUrl);
        
        // 连接到Netty服务器的WebSocket端点
        ws = new WebSocket(wsUrl);

        ws.onopen = function() {
            console.log('WebSocket connection established');
            console.log('WebSocket readyState:', ws.readyState);
            document.getElementById('connectionStatus').className = 'status connected';
            document.getElementById('connectionStatus').innerText = '已连接到服务器';
        };

        ws.onmessage = function(event) {
            console.log('Received message from server:', event.data);
            const message = JSON.parse(event.data);
            console.log('Parsed message object:', message);
            showBarrage(message);
            receivedCount++;
            document.getElementById('receivedCount').innerText = receivedCount;
            console.log('Updated received count:', receivedCount);
        };

        ws.onclose = function() {
            console.log('WebSocket connection closed');
            console.log('WebSocket readyState:', ws.readyState);
            document.getElementById('connectionStatus').className = 'status disconnected';
            document.getElementById('connectionStatus').innerText = '连接已断开，正在重新连接...';
            
            // 5秒后尝试重新连接
            setTimeout(connectWebSocket, 5000);
        };

        ws.onerror = function(error) {
            console.error('WebSocket error:', error);
            document.getElementById('connectionStatus').className = 'status disconnected';
            document.getElementById('connectionStatus').innerText = '连接错误';
        };
    }

    // 发送弹幕
    function sendBarrage() {
        const messageInput = document.getElementById('message');
        const message = messageInput.value.trim();
        
        console.log('Attempting to send barrage message:', message);
        
        if (!message) {
            console.warn('Empty message, not sending');
            alert('请输入弹幕内容');
            return;
        }

        // 构造弹幕消息对象
        const barrageMessage = {
            userId: document.getElementById('userId').value,
            username: document.getElementById('username').value,
            content: message,
            color: document.getElementById('color').value,
            fontSize: parseInt(document.getElementById('fontSize').value),
            position: document.getElementById('position').value
        };

        console.log('Sending barrage message object:', barrageMessage);
        
        // 调用后端/send接口发送弹幕
        fetch('/send', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(barrageMessage)
        })
        .then(response => response.text())
        .then(data => {
            console.log('Server response:', data);
            if (data === 'success') {
                messageInput.value = '';
                sentCount++;
                document.getElementById('sentCount').innerText = sentCount;
                console.log('Updated sent count:', sentCount);
            } else {
                alert('发送失败: ' + data);
            }
        })
        .catch(error => {
            console.error('Error sending barrage message:', error);
            alert('发送失败: ' + error.message);
        });
    }

    // 显示弹幕
    function showBarrage(message) {
        console.log('Displaying barrage message:', message);
        
        const barrageDisplay = document.getElementById('barrageDisplay');
        const barrageItem = document.createElement('div');
        
        barrageItem.className = 'barrage-item';
        barrageItem.innerText = `${message.username}: ${message.content}`;
        barrageItem.style.color = message.color;
        barrageItem.style.fontSize = message.fontSize + 'px';
        
        console.log('Created barrage item with content:', barrageItem.innerText);
        console.log('Barrage item style - color:', message.color, 'fontSize:', message.fontSize);
        
        // 设置弹幕初始位置
        if (message.position === 'top') {
            barrageItem.style.top = '10px';
            barrageItem.style.left = '50%';
            barrageItem.style.transform = 'translateX(-50%)';
            console.log('Positioning barrage at top');
        } else if (message.position === 'bottom') {
            barrageItem.style.bottom = '10px';
            barrageItem.style.left = '50%';
            barrageItem.style.transform = 'translateX(-50%)';
            console.log('Positioning barrage at bottom');
        } else {
            // 滚动弹幕
            const topPosition = Math.random() * (barrageDisplay.offsetHeight - 30);
            barrageItem.style.top = topPosition + 'px';
            barrageItem.style.right = '-200px';
            console.log('Positioning barrage as scrolling, top:', topPosition);
        }
        
        barrageDisplay.appendChild(barrageItem);
        console.log('Appended barrage item to display');
        
        // 动画效果
        if (message.position === 'normal') {
            // 滚动动画
            const animation = barrageItem.animate(
                [
                    { right: '-200px' },
                    { right: barrageDisplay.offsetWidth + 'px' }
                ],
                {
                    duration: 8000,
                    easing: 'linear'
                }
            );
            
            // 动画结束后移除元素
            animation.onfinish = function() {
                barrageItem.remove();
            };
        } else {
            // 固定位置弹幕，5秒后淡出
            setTimeout(() => {
                barrageItem.style.transition = 'opacity 1s';
                barrageItem.style.opacity = '0';
                
                setTimeout(() => {
                    barrageItem.remove();
                }, 1000);
            }, 5000);
        }
    }
</script>
</body>
</html>